package com.disk.filter;

import com.disk.domain.UserLoginDetail;
import com.disk.utils.JwtUtil;
import com.disk.utils.RedisCache;
import com.disk.utils.SecurityConstant;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        String token = request.getHeader(SecurityConstant.HEADER_STRING);
//        String token = request.getHeader("token");
        if(token==null)
        {
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId;
        try {
            token=token.substring(7);
            Claims claims= JwtUtil.parseJWT(token);
            userId=claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("登录失败");
        }
        //从redis中获取用户信息
        String redisKey = "login:"+userId;
        UserLoginDetail userLoginDetail = redisCache.getCacheObject(redisKey);
        if(userLoginDetail==null)
        {
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        //TODO 5.获取权限信息封装到Authentication中,后续实现
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(userLoginDetail,null,userLoginDetail.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request,response);

    }
}
